//
//  PprojectDetailViewController.m
//  wsgz
//
//  Created by huck on 2017/5/9.
//  Copyright © 2017年 BoingPay. All rights reserved.
//

#import "ProjectDetailViewController.h"
#import "AppUtils.h"
#import "HomeManager.h"
#import "MJPhoto.h"
#import "MJPhotoBrowser.h"
#import "XGWebViewController.h"
#import "HttpRequest1.h"
#import "FileUtil.h"


#define kIconSize 40.0

@interface ProjectDetailViewController ()

@property (nonatomic,strong) NSMutableArray *imageViewList;

@end

@implementation ProjectDetailViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubview];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self refreshProgressView];
}

-(void)initSubview
{
    self.title = @"项目详情";
    _imageViewList = [[NSMutableArray alloc] init];
    _progresView.layer.borderColor = [UIColor colorWithString:COLOR_EEEEEE].CGColor;
    // 标题view的的圆角
    CGRect f = CGRectMake(0, 0, SCREEN_WIDTH-40, 40);
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:f byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(3, 3)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = f;
    maskLayer.path = maskPath.CGPath;
    _titleView.layer.mask = maskLayer;
    
    [HomeManager sharedInstance].projectDetailInfo = nil;
    [self requestDetailInfo];
}

-(void)requestDetailInfo
{
    [[HomeManager sharedInstance] requestProjectDetail:_projectId complete:^(BOOL success) {
        [self refreshInfo];
    }];
    
}

//设置界面数据
-(void)refreshInfo
{
    ProjectInfoData *data = [HomeManager sharedInstance].projectDetailInfo;
    _nameLabel.text = data.projectName;
    _typeLabel.text = data.projectTypeName;
    _srartLabel.text = data.startTime;
    _finishLabel.text = data.finishTime;
    _investLabel.text = [NSString stringWithFormat:@"%@ 万",data.planInvest];
    _leaderLabel.text = data.leader;
    _topLeaderLabel.text = data.topLeader;
    _dealLabel.text = data.renovateName;
    _areaLabel.text = data.dutyArea;
    [self refreshProgressView];
    //
    [self initFileViews];
}
//设置项目进度数据
-(void)refreshProgressView
{
    ProjectInfoData *infoData = [HomeManager sharedInstance].projectDetailInfo;
    CGFloat offy = 40;
    UIFont *font = [UIFont systemFontOfSize:13];
    UIColor *color = [UIColor colorWithString:COLOR_494B55];
    for(ProjectProcessData *data in infoData.processList){
        UIView *progressView = [[UIView alloc] initWithFrame:CGRectMake(0, offy, SCREEN_WIDTH-40, 36)];
        progressView.backgroundColor = [UIColor clearColor];
        
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, progressView.width*0.22-20, progressView.height)];
        label1.textAlignment = NSTextAlignmentCenter;
        label1.font = font;
        label1.textColor = color;
        label1.text = [NSString stringWithFormat:@"%zi%@",data.percent,@"%"];
        [progressView addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(label1.right, 0, progressView.width*0.44, progressView.height)];
        label2.textAlignment = NSTextAlignmentCenter;
        label2.font = font;
        label2.textColor = color;
        label2.text = data.detail;
        [progressView addSubview:label2];

        UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(label2.right, 0, progressView.width*0.34, progressView.height)];
        label3.textAlignment = NSTextAlignmentCenter;
        label3.font = [UIFont systemFontOfSize:12];
        label3.textColor = color;

        label3.text = data.finishTime;
        [progressView addSubview:label3];
        
        [_progresView addSubview:progressView];
        offy += progressView.height;
    }
    _progressViewH.constant = offy;
    
    //渐变指示条
    // 颜色从(234,244,255) 变到最后的(24,164,255)渐变
    if(infoData.processList.count>0){
        CGFloat step1 = 2.1;
        CGFloat step2 = 0.8;
        CGFloat start1 = 234;
        CGFloat start2 = 244;
        CGFloat offy = 40 + 36/2;
        ProjectProcessData *process0 = infoData.processList[0];
        UIColor *startColor = [UIColor colorWithRed:(start1-(process0.percent*step1))/255.0 green:(start2-(process0.percent*step2))/255.0 blue:1.0 alpha:1];
        for(int i=0;i<infoData.processList.count;i++){
            ProjectProcessData *process = infoData.processList[i];
            if (i>0) {
                UIColor *endColor = [UIColor colorWithRed:(start1-(process.percent*step1))/255.0 green:(start2-(process.percent*step2))/255.0 blue:1.0 alpha:1];
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(12, offy-36, 2, 36)];
                [_progresView addSubview:line];
                
                [self setGradualColor:line startColor:startColor endColor:endColor];
                startColor = endColor;
            }
            
            UIView *point = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 6, 6)];
            point.layer.cornerRadius = 3;
            point.layer.masksToBounds = YES;
            point.backgroundColor = startColor;
            point.center = CGPointMake(13,offy);
            [_progresView addSubview:point];
            offy += 36;
        }
    }
}

-(void)setGradualColor:(UIView *)v startColor:(UIColor *)startColor endColor:(UIColor *)endColor
{
    //初始化CAGradientlayer对象，使它的大小为UIView的大小
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = v.bounds;
    //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
    [v.layer addSublayer:gradientLayer];
    //设置渐变区域的起始和终止位置（范围为0-1）
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1);
    //设置颜色数组
    gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
}

//设置文件

#pragma mark  ********************文件部分处理[start]************************
//计算文件展示的高度
-(void)caleFileSize
{
    ProjectInfoData *infoData = [HomeManager sharedInstance].projectDetailInfo;
    CGFloat width = (SCREEN_WIDTH -20-20-10-10)/3.0;
    CGFloat minHeight = width*2.0/3.0;  //最小的高度,因为图片3:2
    NSString *minHeightStr =  [NSString stringWithFormat:@"%f",minHeight];
    NSMutableArray *heightArr = [NSMutableArray arrayWithCapacity:infoData.projectFileList.count/3+1];
    for(int i=0;i<infoData.projectFileList.count/3+1;i++){
        [heightArr addObject:minHeightStr];//
    }
    for(int i=0;i<infoData.projectFileList.count;i++){
        ProjectFileData *data = infoData.projectFileList[i];
        CGFloat totalH = minHeight;
        if(![data isPicture]){
            CGFloat labelH = [AppUtils labelSizeWithString:data.fileName font:[UIFont systemFontOfSize:12] maxSize:CGSizeMake(width, SCREEN_HEIGHT)].height;
            totalH =kIconSize+labelH+8.0;//label 上下4
        }
        NSInteger index = i/3;
        CGFloat value = [AppUtils toString:heightArr[index]].floatValue;
        heightArr[index] = [NSString stringWithFormat:@"%f", MAX(totalH, value)];
    }
    for(int i=0;i<infoData.projectFileList.count;i++){
        ProjectFileData *data = infoData.projectFileList[i];
        NSInteger index = i/3;
        data.showHeight = [AppUtils toString:heightArr[index]].floatValue;
    }  
}

//更新照片 上下左右顶死 //图片比例3:2 上下间隔10 左右间隔10
- (void)initFileViews
{
    [self caleFileSize];
    [AppUtils clearSubView:_fileContainerView];
    ProjectInfoData *infoData = [HomeManager sharedInstance].projectDetailInfo;

    UIImageView *imageView = nil;//图片比例3:2
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat stepX = 10;//左右间隔10
    CGFloat StepY = 10;//上下间隔10
    CGFloat kViewWidth = (SCREEN_WIDTH - 20*2 - stepX*2)/3.0;
    CGFloat kViewHeight = kViewWidth*2.0/3.0;
    CGFloat minHeight = kViewHeight;  //最小的高度,也是图片的高度,因为图片3:2
    for (int i = 0; i < infoData.projectFileList.count; i++) {
        ProjectFileData *data = infoData.projectFileList[i];
        kViewHeight = data.showHeight;
        x = (i % 3) * (kViewWidth+stepX);
//        y = (i / 2) * (kImageHeight+StepY);
        UIView *outView = [[UIView alloc] initWithFrame:CGRectMake(x, y, kViewWidth, kViewHeight)];
        [_fileContainerView addSubview:outView];
        
        if([data isPicture]){
            imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (kViewHeight-minHeight)/2, kViewWidth, minHeight)];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.layer.masksToBounds = YES;
            imageView.tag = i;
            [AppUtils setImage:imageView url:data.realpath];
            [outView addSubview:imageView];
            [_imageViewList addObject:imageView];
        }else{
            imageView = [[UIImageView alloc] initWithFrame:CGRectMake((kViewWidth-kIconSize)/2, 0, kIconSize, kIconSize)];
            imageView.contentMode = UIViewContentModeScaleToFill;
            imageView.layer.masksToBounds = YES;
            imageView.image = [UIImage imageNamed:[data getIconName]];
            [outView addSubview:imageView];
            
            UILabel *fileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, kIconSize, kViewWidth, kViewHeight-kIconSize)];
            fileNameLabel.numberOfLines = 0;
            fileNameLabel.font = [UIFont systemFontOfSize:12.0];
            fileNameLabel.textColor = [UIColor colorWithString:COLOR_494B55];
            fileNameLabel.textAlignment = NSTextAlignmentCenter;
            fileNameLabel.text = data.fileName;
            [outView addSubview:fileNameLabel];
        }
        outView.tag = i;
        outView.userInteractionEnabled = YES;
        [outView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewImage:)]];

        if(i%3==2 || i == infoData.projectFileList.count-1){
            y+=kViewHeight + ((i == infoData.projectFileList.count-1) ? 0:StepY);
        }
    }
    _fileViewH.constant = y;
    _fileTitleView.hidden = infoData.projectFileList.count==0;
}
//
//查看缩略图
- (void)viewImage:(UITapGestureRecognizer *)recognizer
{
    ProjectInfoData *infoData = [HomeManager sharedInstance].projectDetailInfo;

    NSInteger index = recognizer.view.tag;
    if(index<0|| index>=infoData.projectFileList.count){
        return;
    }
    ProjectFileData *data = infoData.projectFileList[index];
    if(data.isPicture){
        NSMutableArray *photos = [[NSMutableArray alloc] init];
        MJPhoto *photo = nil;
        UIImageView *imageView = nil;
        for (int i = 0; i < _imageViewList.count; i++) {
            imageView = [_imageViewList objectAtIndex:i];
            if (imageView.hidden) {
                continue;
            }
            photo = [[MJPhoto alloc] init];
            photo.image = imageView.image;
            photo.srcImageView = imageView;
            [photos addObject:photo];
        }
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.photos = photos;
        browser.currentPhotoIndex = recognizer.view.tag;
        [browser show];
    }else{
//        //下载到本地,然后本地webview打开
//        http://120.26.232.187:81/fivewater/upload/files/20170603141046dhT88XL1.xls
        NSString *fileName = [data.realpath lastPathComponent];
        NSString *filePatn = [[FileUtil getUpdateDir:infoData.projectId cacheType:nil] stringByAppendingPathComponent:fileName];

        if([FileUtil exists:filePatn]){//存在
            [self openFile:filePatn title:data.fileName];
        
        }else{//不存在
            __weak ProjectDetailViewController *weakSelf = self;
            [Toast loading];
            [[HttpRequest1 sharedHttpRequest] download:data.realpath params:nil filePath:filePatn process:^(long long writeBytes, long long totalBytes) {
//                NSLog(@"%lli--%lli",writeBytes,totalBytes);
            } complete:^(BOOL success, NSDictionary *result) {
                [Toast loaded];
                if(success){
                    [weakSelf openFile:filePatn title:data.fileName];
                }else{
                    [Toast makeText:@"文件打开失败,请重新操作"];
                    [FileUtil deleteFile:filePatn];
                }
            }];
        }
    }
}


-(void)openFile:(NSString *)filePath title:(NSString *)title
{
    NSURL* url = [NSURL fileURLWithPath:filePath];
    XGWebViewController *web = [[XGWebViewController alloc] init];
    web.url = url.absoluteString;
    web.hideRightButton = YES;
    web.customTitle = title;
    [[AppUtils getNavigationController] pushViewController:web animated:YES];
}

#pragma mark  ********************文件部分处理[end]************************




@end
